<?php
require_once "site_config.php";
require_once "ra_global.php";

$method = $_GET['method'];
// 店长积分商品兑换
if($method == "exchangeOwnerScore"){
    $userid = $_GET['userid'];
    $shopid = $_GET['shopid'];
    $postfee = $_GET['postfee'];
    $totalscore = $_GET['totalscore'];
    $totalnum = $_GET['totalnum'];
    $selected = $_GET['selectedarray'];
	$contactname = $_GET['contactname'];
	$contactphone = $_GET['contactphone'];
	$contactaddress = $_GET['contactaddress'];

    $selectedArray = json_decode($selected, true);

    echo exchangeOwnerScore($db, $userid, $shopid, $postfee, $totalscore, $totalnum, $selectedArray, $contactname, $contactphone, $contactaddress);
}
// 合法性check
else if ($method == "checkStatus") {
    $userid = $_GET['userid'];
    $selected = $_GET['selectedarray'];
    $selectedArray = json_decode($selected, true);

    echo checkStatus($db, $userid, $selectedArray);
}

function checkStatus($db, $userid, $selectedArray) {
    $result = array();

	// 实物不能兑换超出库存，虚拟物品不能兑换超出未使用兑换码总数
	foreach($selectedArray as $selected) {
		$productId = $selected['productid'];
        $num = $selected['num'];
        $product=$db->ig2_want('mae_admin_product','id='.$productId);
		
		if ($product['isvirtual'] == 0) {
			if ($num > $product['stock']) {
				$result['errcode'] = 1;
				$result['errmsg'] = $product['name'].':超出库存上限';
				return json_encode($result);
			}
		} else if ($product['isvirtual'] == 1) {
			$virtualList=$db->ig2_select('mae_admin_product_virtual','productid = '.$productId.' and isused = 0');
			if ($num > count($virtualList)) {
				$result['errcode'] = 1;
				$result['errmsg'] = $product['name'].':超出兑换码上限';
				return json_encode($result);
			}
		}
	}
    // 普通商品兑换每月不能超1500分, 
    $normalProductScore = 0;
    foreach($selectedArray as $selected) {
        if ($selected['type'] == 2) {
            $productId = $selected['productid'];
            $num = $selected['num'];
            $product=$db->ig2_want('mae_admin_product','id='.$productId);

            $normalProductScore += $num * $product['score'];
        }
    }

    $stime=date('Y-m-01', strtotime(date("Y-m-d")));//当月开始时间 Y-m-d格式
    $etime=strtotime("$stime +1 month");//当月结束时间 时间戳
    $stime=strtotime($stime);//当月开始时间 时间戳
    $normalExchangedList=$db->ig2_select('mae_admin_product_exchange_detail_log','userid = '.$userid.' and userange = 2 and createtime >= '.$stime.' and createtime < '.$etime);

    foreach($normalExchangedList as $exchanged) {
        $normalProductScore += $exchanged['num'] * $exchanged['score'];
    }

    if ($normalProductScore > 1500) {
        $result['errcode'] = 1;
        $result['errmsg'] = '每月兑换普通商品的积分不能超过1500积分';
        return json_encode($result);
    }

    // 兑换积分不能大于总积分
    $exchangedScore = 0;
    foreach($selectedArray as $selected) {
        $productId = $selected['productid'];
        $num = $selected['num'];
        $product=$db->ig2_want('mae_admin_product','id='.$productId);
        $exchangedScore += $num * $product['score'];
    }

    $shop = $db->ig2_want('mae_shop', 'admin_id = '.$userid);
    if ($shop && $shop['quadratic'] < $exchangedScore) {
        $result['errcode'] = 1;
        $result['errmsg'] = '积分不足！';
        return json_encode($result);
    }

    $result['errcode'] = 0;
    return json_encode($result);
}
function exchangeOwnerScore($db, $userid, $shopid, $postfee, $totalscore, $totalnum, $selectedArray, $contactname, $contactphone, $contactaddress) {
    $checkResult = json_decode(checkStatus($db, $userid, $selectedArray), true);
    if ($checkResult['errcode'] == 1) {
        return json_encode($checkResult);
    }

    $result = array();

    $success = true;
    $db->ig2_query('BEGIN');
    $result1 = false;

    // 插入总日志记录
    $result1=$db->ig2_query('INSERT INTO mae_admin_product_exchange_summary_log(userid, shopid, totalnum, totalscore, postfee, createtime) VALUES ('.$userid.', '.$shopid.', '.$totalnum.', '.$totalscore.', '.$postfee.', '.time().')');
    $summaryId = mysql_insert_id();
    $success=$success && $result1?true:false;

    // 插入明细记录
    foreach($selectedArray as $selected) {
        if ($success) {
            $productId = $selected['productid'];
            $num = $selected['num'];
            $productName='';
            $product=$db->ig2_want('mae_admin_product','id='.$productId);
            if ($product) {
                $productName = $product['name'];
            }
			
			$result1=$db->ig2_query("INSERT INTO mae_admin_product_exchange_detail_log(summaryid, userid, shopid, productid, productname, num, createtime, status, contactname, contactphone, contactaddress, score, userange, isvirtual) VALUES (".$summaryId.", ".$userid.", ".$shopid.", ".$productId.", '".$productName."', ".$num.", ".time().", 0, '".$contactname."', '".$contactphone."', '".$contactaddress."', ".$product['score'].", ".$product['userange'].", ".$product['isvirtual'].")");
			$detailId = mysql_insert_id();
            $success=$success && $result1?true:false;
			
			if ($success) {
				if ($product['isvirtual'] == 1) {
					$virtualList=$db->ig2_select('mae_admin_product_virtual','productid = '.$productId.' and isused = 0 limit '.$num);
					foreach($virtualList as $virtual) {
						if ($success) {
							$result1=$db->ig2_query("INSERT INTO mae_admin_product_exchange_detail_log_virtual(detaillogid, cardnum, password, createtime) VALUES (".$detailId.", '".$virtual['cardnum']."', '".$virtual['password']."', ".time().")");
							$result1=$db->ig2_query("UPDATE mae_admin_product_virtual SET isused = 1 WHERE id = ". $virtual['id']);
							$success=$success && $result1?true:false;
						}
					}
				}
			}

			if ($success) {
				if ($product['isvirtual'] == 0) {
					// 扣库存
					$result1=$db->ig2_query("UPDATE mae_admin_product SET stock=stock-".$num.' WHERE id='.$productId);
					$success=$success && $result1?true:false;
				}
			}
        }
    }

    // 店铺积分扣除
    $result1=$db->ig2_query("UPDATE mae_shop SET quadratic=quadratic-".$totalscore.' WHERE id='.$shopid);
	$success=$success && $result1?true:false;

    if ($success) {
        $db->ig2_query('COMMIT');
        $result['errcode'] = 0;
    } else {
        $db->ig2_query('ROLLBACK');
        $result['errcode'] = 1;
        $result['errmsg'] = '服务器异常';
    }

    return json_encode($result);
}
?>